/***************************************************************************************************
This program uses our baseline sufficient statistic to compute the welfare gain asset class by asset class

It requires a dataset with the following variable: 
transactions: nt_housing_total, deposits_total, debt_total, nt_equity_total
prices: R0t_adhoc, PDh_shock, Qd_shock, Qm_shock, PDe_shock (available from the dataset Save/prices.dta)

If xi != 0 (i.e. extension for borrowing constraints and collateral effects), it also requires ltv, the loan-to-value ratio, and ltv_debt, the loan-to-value ratio times debt. This option is only used on the micro-data.
***************************************************************************************************/
program define gen_welfare
	syntax [, by(varlist) xi(real 0.0)]
	if "`by'" != ""{
		local egenby by(`by')
	}


	/* adjust discount factor if xi != 0*/
	if `xi' == 0{
		gen R0t = R0t_adhoc
	}
	else{
		tempvar adjustment
		bysort `by' (year): gen `adjustment' = sum(- 2 * `xi' * clip(ltv, 0, 1) * (year >= 1994))
		gen R0t = R0t_adhoc * exp(`adjustment')
	}

	/* compute welfare gains */
	egen welfare_housing = sum(-R0t * nt_housing_total * PDh_shock * (year >= 1994)), `egenby'
	egen welfare_deposits = sum(-R0t * deposits_total * Qd_shock * (year >= 1994)), `egenby'
	egen welfare_debt = sum(R0t * debt_total * Qm_shock * (year >= 1994)), `egenby'
	egen welfare_equity = sum(-R0t * nt_equity_total * PDe_shock * (year >= 1994)), `egenby'
	if `xi' == 0{
		gen welfare_collateral = 0.0
	}
	else{
		egen welfare_collateral = sum(R0t * ltv_debt * `xi' * PDh_shock * (year >= 1994)), `egenby'
	}
	gen welfare_total = welfare_housing + welfare_deposits + welfare_debt + welfare_equity + welfare_collateral

	/* compute reevaluation gains */
	egen revgain_housing = sum(R0t * housing_total * reh_shock), `egenby'
	gen revgain_deposits = 0.0
	gen revgain_debt = 0.0
	egen revgain_equity = sum(R0t * equity_total * ree_shock), `egenby'
	gen revgain_total = revgain_housing + revgain_equity

	keep if year == 1994
end
